package com.michaelbulava.TFS;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.michaelbulava.TFS.jni.NativesHelper;
import com.michaelbulava.TFS.log.FileLogger;
import org.jetbrains.annotations.NotNull;

import java.io.File;

/**
 * Created by mbulava on 5/6/2015.
 */
public class TFSVcsApplicationComponent implements ApplicationComponent {
    private Logger log; //Can't make this static in ApplicationComponent, guessing it has to due with an order of
    // operations since it's using propertiesComponent which is another AppComp
    public static final String PLUGIN_ID = "com.michaelbulava.TFSVCS";
    private static final String DEBUG_NATIVES_LOCATION = "C:\\Users\\MichaelA\\IdeaProjects\\TFSVcs\\lib\\TFS-SDK 14.0.1\\os";
    private static TFSVcsApplicationComponent instance = null;

    public TFSVcsApplicationComponent() {
        log = FileLogger.getInstance(TFSVcsApplicationComponent.class);
    }

    public void initComponent() {
        log.info("initComponent - Starting");
        //initialize the Natives
        instance = this;
        ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
            @Override
            public void run() {
                try{
                    log.info("Detecting natives setup");
                    if (!NativesHelper.isNativeSet()) {
                        if (!NativesHelper.tryToSetNatives()) {
                            if (!isDebugMode()) {
                                Messages.showErrorDialog("Missing Native files for Team foundation server, the plugin will not function correctly, please make sure you have a valid installation and reinstall the plugin", "Missing Dependancies");
                                throw new RuntimeException("Unable to start Plugin without required native components.");
                            } else {
                                log.warn("Trying Debug Natives location");
                                File nativeLocation = new File(DEBUG_NATIVES_LOCATION);
                                if (!nativeLocation.exists())
                                    throw new RuntimeException("Unable to start Plugin without required native components.");


                                //com.intellij.openapi.ui.Messages.showInfoMessage("Natives do not exist in plugin location, but have be located at the DEBUG_NATIVES_LOCATION.  We will load these now.", "Testing Mode");
                                NativesHelper.setNativeLocation(new File(DEBUG_NATIVES_LOCATION));
                            }
                        }
                    }
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            onAfterNativesAttached();
                        }
                    });

                } catch(Throwable tr){
                    log.error("Error occured during init", tr);
                    final String ErrorMessage = tr.getMessage();

                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Messages.showErrorDialog("Failed to initialize Team Foundation Server version control system with error:\n"
                                    + ErrorMessage, "Failed to start Component");
                        }
                    });
                }
            }
        });

    }

    public void disposeComponent() {
        if (NativesHelper.isNativeSet())
            NativesHelper.clearNativeLocation();
        instance = null;
        log.info("disposeComponent - Completed");
    }


    @NotNull
    public String getComponentName() {
        return "TFSVcsApplicationComponent";
    }

    private static boolean isDebugMode(){
        boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().
                getInputArguments().toString().indexOf("-agentlib:jdwp") > 0;
        return isDebug;
    }

    public static TFSVcsApplicationComponent getInstance(){
        return instance;
    }

    private final void onAfterNativesAttached(){

    }
}
